Examples of plotly

We’re gonna look at NYC Airbnb data.

library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6      ✔ purrr   0.3.4 
## ✔ tibble  3.1.8      ✔ dplyr   1.0.10
## ✔ tidyr   1.2.1      ✔ stringr 1.4.1 
## ✔ readr   2.1.2      ✔ forcats 0.5.2 
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(p8105.datasets)
library(plotly)
## 
## 载入程辑包:'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout

Loading data

data("nyc_airbnb")

nyc_airbnb = 
  nyc_airbnb %>%
  mutate(rating = review_scores_location / 2) %>%
  select(neighbourhood_group, neighbourhood, rating, price, room_type, lat, long) %>%
  filter(
    neighbourhood_group == "Manhattan",
    price %in% 100:500,
    room_type == "Entire home/apt"
  ) %>%
  drop_na(rating)

Plotly plots

Sctterplot

nyc_airbnb %>%
  plot_ly(x= ~lat, y = ~long, color = ~price, alpha = .5, 
          type = "scatter", mode = "markers")
nyc_airbnb %>%
  plot_ly(x= ~lat, y = ~long, color = ~price, text = ~rating, alpha = .5, 
          type = "scatter", mode = "markers")
nyc_airbnb %>%
  mutate(text_label = str_c("Price : $", price, "\nRating:", rating)) %>%
  plot_ly(x= ~lat, y = ~long, color = ~price, text = ~rating, alpha = .5, 
          type = "scatter", mode = "markers")

boxplots

nyc_airbnb %>%
  plot_ly(y = ~price, x = ~neighbourhood, color = ~neighbourhood,
          type = "box")
## Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large, allowed maximum for palette Set2 is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large, allowed maximum for palette Set2 is 8
## Returning the palette you asked for with that many colors
nyc_airbnb %>%
  mutate(neighbourhood = fct_reorder(neighbourhood, price))%>%
  plot_ly(y = ~price, x = ~neighbourhood, color = ~neighbourhood,
          type = "box")
## Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large, allowed maximum for palette Set2 is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large, allowed maximum for palette Set2 is 8
## Returning the palette you asked for with that many colors

bar plot

nyc_airbnb %>%
  count(neighbourhood) %>%
  mutate(neighbourhood = fct_reorder(neighbourhood, n))%>%
  plot_ly(x = ~neighbourhood, y = ~n, color = ~neighbourhood, type = "bar", colors ="viridis")